﻿using Microsoft.Extensions.Logging;
using NewLife.MQTT;
using System.Net;

namespace SimpleX.System
{
	public class MQTTService : IMQTTService
	{
		private readonly ILogger<MQTTService> _logger;
		private readonly IConfigService _configService;
		public MQTTService(ILogger<MQTTService> logger, IConfigService configService)
		{
			_logger = logger;
			_configService = configService;
		}

		public async Task<MQTTConfig> GetMQTTConfig()
		{
			var list = await _configService.GetListByCategory(CateGoryConst.Config_MQTT_BASE);
			return new MQTTConfig
			{
				Url = list?.FirstOrDefault(x => x.ConfigKey == "MQTT_PARAM_URL")?.ConfigValue,
				Server = list?.FirstOrDefault(x => x.ConfigKey == "MQTT_PARAM_SERVER")?.ConfigValue,
				UserName = list?.FirstOrDefault(x => x.ConfigKey == "MQTT_PARAM_USERNAME")?.ConfigValue,
				Password = list?.FirstOrDefault(x => x.ConfigKey == "MQTT_PARAM_PASSWORD")?.ConfigValue,
			};
		}

		public async Task<bool> Publish(string topic, object data)
		{
			var config = await GetMQTTConfig();
			if (string.IsNullOrEmpty(config?.Url))
			{
				throw new Exception($"MQTT Server 没有配置");
			}

			var _mqttClient = new MqttClient
			{
				Server = config.Server,
				UserName = config.UserName,
				Password = config.Password,
				ClientId = $"SimpleX_{Dns.GetHostName()}",
				Reconnect = false
			};

			try
			{
				await _mqttClient.ConnectAsync();
				await _mqttClient.PublishAsync(topic, data);
				return true;
			}
			catch (Exception ex)
			{
				_logger.LogError(exception: ex, message: "MQTT Publish");
			}
			finally
			{
				await _mqttClient.DisconnectAsync();
				_mqttClient.Dispose();
			}

			return false;

			// 订阅“/test”主题
			//var rt = await client.SubscribeAsync("/test", (e) =>
			//{
			//	XTrace.WriteLine("收到消息:" + "/test/# =>" + e.Topic + ":" + e.Payload.ToStr());
			//});

			// 每2秒向“/test”主题发布一条消息
			//while (true)
			//{
			//	try
			//	{
			//		var msg = "学无先后达者为师" + Rand.NextString(8);
			//		await client.PublishAsync("/test", msg);
			//	}
			//	catch (Exception ex)
			//	{
			//		XTrace.WriteException(ex);
			//	}
			//	await Task.Delay(2000);
			//}
		}
	}
}
